<!--
 * @Author: hpc(hepch)
 * @Date: 2021-04-26 11:46:49
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-10-15 10:08:32
 * @Description: file content
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->

<template>
  <div id="suspendedsearchresult">
    <div class="card-isExpend" v-show="isExpendCard" @click="isExpend">
      展开结果面板
    </div>
    <a-card
      class="search-result-card"
      title="日新图详情:"
      size="small"
      v-show="visible"
    >
      <div slot="extra">
        <a-form layout="inline" style="float: left">
          <a-form-item label="显示范围">
            <a-switch default-checked @change="onChange" />
          </a-form-item>
          <a-form-item>
            <a-button size="small" @click="isExpend" type="link">
              <a-icon type="down"></a-icon
            ></a-button>
            <a-button size="small" @click="onClose" type="link">
              <a-icon type="close"></a-icon
            ></a-button>
          </a-form-item>
        </a-form>
      </div>
      <div class="container">
        <a-table
          :loading="tableloading"
          :columns="columns"
          :data-source="tabledata"
          size="small"
          bordered
          :pagination="{ pageSize: 50 }"
          :row-selection="{ onSelect: onSelect, onSelectAll: onSelectAll }"
        ></a-table>
      </div>
    </a-card>
  </div>
</template>

<script>
// import setVuexLayerGroup from "../../Map/setVuexLayerGroup";
// import moment from "moment";
import L from "leaflet";
import { showBottomPanel, hideBottomPanel } from "@/utils/divResize";
const columns = [
  {
    dataIndex: "index",
    key: "index",
    title: "ID",
  },
  {
    dataIndex: "appid",
    key: "appid",
    title: "服务ID",
  },
  {
    dataIndex: "imagedate",
    key: "imagedate",
    title: "影像获取时间",
  },
  {
    dataIndex: "range",
    key: "range",
    title: "空间范围",
  },
  {
    dataIndex: "maxlevel",
    key: "maxlevel",
    title: "最大切片级别",
  },
  {
    dataIndex: "resolution",
    key: "resolution",
    title: "影像分辨率",
  },
  {
    dataIndex: "cloudpercent",
    key: "cloudpercent",
    title: "云量",
  },
  {
    dataIndex: "imagetype",
    key: "imagetype",
    title: "影像类型",
  },
  {
    dataIndex: "satelliteid",
    key: "satelliteid",
    title: "卫星类型",
  },
  {
    dataIndex: "id",
    key: "id",
    title: "影像文件名",
  },
];
export default {
  data() {
    return {
      columns,
      tabledata: [],
      visible: false,
      layersIds: {},
      tableloading: true,
      isExpendCard: false,
      layererror: undefined,
      myIcon: L.divIcon({
        html: "影像缺失",
        className: "my-div-icon",
        iconSize: 30,
      }),
    };
  },
  computed: {
    suspendedGroup() {
      return this.$store.state.suspendedGroup;
    },
    map() {
      return this.$store.state.map;
    },
    boundsGroup() {
      return L.featureGroup().addTo(this.suspendedGroup);
    },
  },

  methods: {
    isExpend() {
      this.visible = !this.visible;
      this.isExpendCard = !this.isExpendCard;
      this.visible ? showBottomPanel() : hideBottomPanel();
    },
    onChange(checked) {
      if (checked) {
        this.boundsGroup.addTo(this.suspendedGroup);
      } else {
        this.boundsGroup.removeFrom(this.suspendedGroup);
      }
    },
    //移除添加的地图
    removemap(layerid) {
      this.suspendedGroup.removeLayer(layerid);
    },
    //点击日新图列表，添加到地图
    addmap(item, coor) {
      let corner1 = L.latLng(item.geom.bbox[1], item.geom.bbox[0]);
      let corner2 = L.latLng(item.geom.bbox[3], item.geom.bbox[2]);

      let wmtsBounds = L.latLngBounds(corner2, corner1);

      corner1 = L.latLng(coor[0][0], coor[0][1]);
      corner2 = L.latLng(coor[2][0], coor[2][1]);
      console.log(coor);
      let imgBounds = L.latLngBounds(corner1, corner2);
      this.map.fitBounds(imgBounds);
      // let imageUrl =
      //   "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg";
      // let imageBounds = wmtsBounds;
      // L.imageOverlay(imageUrl, imageBounds).addTo(this.suspendedGroup);
      // L.gridLayer().addTo(this.map);
      //L.marker(<LatLng> latlng, <Marker options> options?)
      // var myIcon = L.icon({
      //   iconUrl: "my-icon.png",
      //   iconSize: [38, 95],
      //   iconAnchor: [22, 94],
      //   popupAnchor: [-3, -76],
      //   shadowUrl: "my-icon-shadow.png",
      //   shadowSize: [68, 95],
      //   shadowAnchor: [22, 94],
      // });
      // L.marker([wmtsBounds.getCenter().lat, wmtsBounds.getCenter().lng], {
      //   icon: myIcon,
      // }).addTo(this.suspendedGroup);

      let wmtsurl = window.getSuspendedHost();
      let layer = L.supermap.wmtsLayer(wmtsurl, {
        layer: item.appid,
        style: "defult",
        tilematrixSet: "EPSG:3857",
        format: "image/png",
        requestEncoding: "KVP",
        bounds: wmtsBounds,
        errorTileUrl: "@/assets/imgs/nopng.png",
      });

      // console.log(layer.getTileUrl());
      // layer = L.tileLayer.wms(
      //   "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
      //   {
      //     layers: "nexrad-n0r-900913",
      //     format: "image/png",
      //     transparent: true,
      //     errorTileUrl: "../../../assets/imgs/nopng.png",
      //   }
      // );
      // layer = L.tileLayer("http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png", {
      //   foo: "bar",
      //   bounds: wmtsBounds,
      //   errorTileUrl: "../../../assets/imgs/nopng.png",
      // });
      let self = this;
      layer.on("tileerror", () => {
        if (self.layererror) {
          let layerid = self.suspendedGroup.getLayerId(self.layererror);
          let layerbyid = self.suspendedGroup.getLayer(layerid);
          self.suspendedGroup.removeLayer(layerbyid);
        }
        self.layererror = L.marker(wmtsBounds.getCenter(), {
          icon: self.myIcon,
        }).addTo(self.suspendedGroup);
        setTimeout(() => {
          if (self.layererror) {
            let layerid = self.suspendedGroup.getLayerId(self.layererror);
            let layerbyid = self.suspendedGroup.getLayer(layerid);
            self.suspendedGroup.removeLayer(layerbyid);
          }
        }, 5000);
      });

      layer.addTo(this.suspendedGroup).setZIndex(4);
      this.layersIds[item.appid] = this.suspendedGroup.getLayerId(layer);
    },

    getAllmapsData(obj) {
      if (obj) {
        this.boundsGroup.clearLayers();
        this.suspendedGroup.clearLayers();
        this.boundsGroup.addTo(this.suspendedGroup);
        if (obj.data.length) {
          this.buildTableData(this.sort(obj.data));
          this.addbounds(this.sort(obj.data));
        }
      }
    },
    sort(array) {
      for (var i = 0; i < array.length; i++) {
        for (var j = i + 1; j < array.length; j++) {
          array[i].appid ? "" : (array[i].appid = 0);
          array[j].appid ? "" : (array[j].appid = 0);
          if (array[i].appid > array[j].appid) {
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
          }
        }
        // if (obj[i].childre.length) this.jsonsort(obj[i].children);
      }
      return array;
    },
    buildTableData(array) {
      this.tabledata = [];
      let self = this;

      array.map((item, index) => {
        let obj = item;
        let box = item.geom.bbox;
        obj.index = index + 1;
        obj.key = item.appid;
        obj.imagedate = `${item.imageYear}/${item.imageMonth}/${item.imageDay}`;
        obj.range = `[
            ${box[2].toFixed(2)},
            ${box[3].toFixed(2)},
            ${box[0].toFixed(2)},
            ${box[1].toFixed(2)}
          ]`;
        self.tabledata.push(obj);
      });

      showBottomPanel();

      this.visible = true;
      setTimeout(function () {
        self.tableloading = false;
      }, 500);
      this.$parent.visible = true;
    },
    getBounds(item) {
      let coor = [];
      item.geom.coordinates[0][0].map((item) => {
        let reverse = [item[1], item[0]];
        coor.push(reverse);
      });
      return coor;
    },
    //添加影像范围框
    addbounds(items) {
      for (let i = 0; i < items.length; i++) {
        let item = items[i];
        let coor = [];
        item.geom.coordinates[0][0].map((item) => {
          let reverse = [item[1], item[0]];
          coor.push(reverse);
        });

        let content = `<div class="ant-table ant-table-scroll-position-left ant-table-small" style="max-height: 200px;overflow-y: scroll; border:none;cursor: pointer;">
                        <div class="ant-table-content">
                          <div class="ant-table-body">
                            <table class="">
                              <thead class="ant-table-thead">
                              <tr>
                                <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性名</span><span class="ant-table-column-sorter"></span></div></span></th>
                                <th  class=""><span class="ant-table-header-column"><div><span class="ant-table-column-title">属性值</span><span class="ant-table-column-sorter"></span></div></span></th>
                              </tr>
                              </thead>
                              <tbody class="ant-table-tbody">
                                <tr class="ant-table-row ant-table-row-level-0" >
                                    <td class="" style="border:none">服务ID</td>
                                    <td class="" style="border:none">${item.appid}</td>
                                  </tr>
                                    <tr class="ant-table-row ant-table-row-level-0" >
                                    <td class="" style="border:none">影像获取时间</td>
                                    <td class="" style="border:none">${item.imagedate}</td>
                                  </tr>
                                    <tr class="ant-table-row ant-table-row-level-0" >
                                    <td class="" style="border:none">最大切片级别</td>
                                    <td class="" style="border:none">${item.maxlevel}</td>
                                  </tr>
                                    <tr class="ant-table-row ant-table-row-level-0" >
                                    <td class="" style="border:none">卫星类型</td>
                                    <td class="" style="border:none">${item.satelliteid}</td>
                                  </tr>
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </div>`;
        L.polygon(coor, {
          color: "#ff0000",
          fillOpacity: 0,
        })
          .addTo(this.boundsGroup)
          .bindPopup(content);
      }

      this.map.fitBounds(this.boundsGroup.getBounds());
    },
    onClose() {
      this.suspendedGroup.clearLayers();
      this.layersIds = [];
      this.tabledata = [];
      this.tableloading = true;
      this.visible = false;

      hideBottomPanel();
    },
    onSelect(item, selected) {
      if (selected == false) {
        let layerid = this.layersIds[item.appid];
        this.removemap(layerid);
      } else {
        this.addmap(item, this.getBounds(item));
      }
    },
    onSelectAll(selected, selectedRows) {
      for (let l in this.layersIds) {
        this.removemap(this.layersIds[l]);
      }
      if (selected == true) {
        selectedRows.map((item) => {
          this.addmap(item, this.getBounds(item));
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
#suspendedsearchresult {
  .card-isExpend {
    position: fixed;
    z-index: 999;
    left: 40%;
    bottom: 10px;
    width: 200px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    user-select: none;
    cursor: pointer;
    background-color: #fff;
    border-radius: 15px 15px 0 0;
    color: rgba(0, 0, 0, 0.85);
    border: 1px solid #d9d9d9;
  }
  .search-result-card {
    position: fixed;
    z-index: 99;
    right: 350px;
    left: 0;
    z-index: 999999;
    bottom: 0;
    .container {
      height: 320px;
      margin-top: 3px;
      overflow: scroll;
    }
  }
  /deep/.ant-card-extra {
    padding: 0 !important;
  }
  /deep/.ant-card-body {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
  }
  /deep/.ant-tabs-bar {
    margin: 0 !important;
  }
  /deep/.ant-table-pagination.ant-pagination {
    margin: 5px 0 !important;
    float: right;
  }
  /deep/.ant-table-body {
    overflow-x: scroll;
  }
  /deep/.ant-card-small
    > .ant-card-head
    > .ant-card-head-wrapper
    > .ant-card-extra {
    padding: 0;
  }
}
</style>
